package team.seekers.hula.course.courseUser.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.seekers.hula.course.courseUser.dao.CourseUserDao;
import team.seekers.hula.course.courseUser.entity.dao.CourseUserDO;
import team.seekers.hula.course.courseUser.entity.dto.CourseUserBatchBindDTO;

import java.util.ArrayList;
import java.util.List;

@Service
public class CourseUserManageService {


    @Autowired
    private CourseUserDao userCourseDao;


    @Transactional
    public void batchBind(CourseUserBatchBindDTO courseUserBatchBindDTO) {
        List<CourseUserDO> courseUserDOS = new ArrayList<>();
        for (String courseId : courseUserBatchBindDTO.getCourseIds()) {
            for (String userId : courseUserBatchBindDTO.getUserIds()) {
                CourseUserDO courseUserDO = new CourseUserDO();
                courseUserDO.setCourseId(courseId);
                courseUserDO.setUserId(userId);
                courseUserDO.setRole(courseUserBatchBindDTO.getRole());
                courseUserDOS.add(courseUserDO);
            }

            // 去重
            List<CourseUserDO> exists = userCourseDao.lambdaQuery()
                    .in(CourseUserDO::getUserId, courseUserBatchBindDTO.getUserIds())
                    .eq(CourseUserDO::getCourseId, courseId).list();
            courseUserDOS.removeAll(exists);
        }
        userCourseDao.saveOrUpdateBatch(courseUserDOS);
    }

    @Transactional
    public void unbind(String userId, String courseId) {
        // TODO 删除所有学习记录

        LambdaQueryWrapper<CourseUserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseUserDO::getUserId, userId);
        queryWrapper.eq(CourseUserDO::getCourseId, courseId);
        userCourseDao.remove(queryWrapper);
    }
}
